#include "stdafx.h"
#include "XWebView.h"

XWebView::XWebView() : SOUI::SHostWnd(_T("LAYOUT:XML_X_WEB_WND")) {
}

XWebView::~XWebView() {
}

BOOL XWebView::OnInitDialog(HWND wndFocus, LPARAM lInitParam) {

    m_pLoading = FindChildByName2<SOUI::SWindow>("wnd_loading");
    m_pWebView = FindChildByName2<SOUI::SMBWebView>("__web");
    if (m_pWebView) {
        m_pWebView->GetEventSet()->subscribeEvent(SOUI::EventMBBrowserUrlChanged::EventID,
                SOUI::Subscriber(&XWebView::loadCompleted, this));
    }
    
    m_pWebView->HookUrl([this](const char *url, void *job) {
    
        if (m_url_callback && m_url_callback(url, job)) {
            return TRUE;
        }
        
        return FALSE;
    });
    doLoadURL();
    
    m_pWebView->HookJS([this](int customMsg, const char *jsArg) {
    
    
    });
    
    return FALSE;
}

HRESULT XWebView::OnLanguageChanged() {
    SOUI::SHostWnd::OnLanguageChanged();
    
    if (m_pWebView) {
        doLoadURL();
    }
    return 0;
}

void XWebView::doLoadURL() {
    if (!m_url.IsEmpty()) {
        if (m_pWebView) {
            SOUI::SStringW realUrl = m_url;
            
            if (m_pWebView->GetURL().CompareNoCase(realUrl.c_str()) != 0) {
                m_pWebView->LoadURL(realUrl.c_str());
                KillTimer(10);
                SetTimer(10, 5000);
                if (m_pLoading) {
                    m_pLoading->SetVisible(TRUE, TRUE);
                }
            } else {
                reloadUrl(realUrl);
            }
        }
    } else {
        if (m_pWebView) {
            m_pWebView->LoadURL(L"about:blank");
        }
    }
}

void XWebView::loadUrl(const SOUI::SStringW &url) {
    if (m_url != url) {
        m_url = url;
        doLoadURL();
    }
}

void XWebView::reloadUrl(const SOUI::SStringW &url) {
    if (m_url != url) {
        m_url = url;
        doLoadURL();
    } else if(m_pWebView) {
        m_pWebView->ReLoad();
    }
}

SOUI::SMBWebView *XWebView::getWebView() {
    return m_pWebView;
}

void XWebView::HookUrl(SOUI::hook_url_call call) {
    m_url_callback = call;
}

bool XWebView::loadCompleted(SOUI::EventMBBrowserUrlChanged *arg) {

    KillTimer(10);
    if (m_pLoading) {
        m_pLoading->SetVisible(FALSE, TRUE);
    }
    return false;
}

void XWebView::OnTimer(UINT_PTR idEvent) {
    SetMsgHandled(FALSE);
    if (idEvent == 10) {
        KillTimer(idEvent);
        if (m_pLoading) {
            m_pLoading->SetVisible(FALSE, TRUE);
        }
    } else {
        __super::OnTimer(idEvent);
    }
}
